package ApptUtil;

import CreatorUtil.*;
import LoginUtil.User;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import persistent.Db4oServletListener;

import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Predicate;


/**
 * Servlet implementation class RequestApptServlet
 */
public class RequestApptServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		ObjectContainer container = 
	        (ObjectContainer)request.getAttribute(Db4oServletListener.KEY_DB4O_SESSION);
		
		String datetime = request.getParameter("datetime");
		String reason = request.getParameter("reasonbox");
		String doctor = request.getParameter("doctordrop");
		Appointment appt = new Appointment();
		
		// set up the parser to parse a string into a date-time
		appt.setReasons(reason);
		DateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
		
		// set up the predicate to query the database for a doctor
		final String[] splits = doctor.split(" ");	// split the string around spaces hopefully to separate first and last name
				
		Predicate<User> pred = new Predicate<User>() {
					
					      public boolean match(User doc){
					        return doc.getUserType() == User.UserType.Doctor
					          && doc.getFirstName().equalsIgnoreCase(splits[1])
					          && doc.getLastName().equalsIgnoreCase(splits[2]);}};
		
		try {
			Date date = format.parse(datetime);
			
			ObjectSet<User> rs = container.query(pred);
			if(rs.size() != 1) {
				System.out.println("Doctor field not valid\n");
				response.sendRedirect("apptError.jsp");
				return;
			}

			appt.setDateTime(date);
			appt.setDoc(rs.next());
			
			container.store(appt);
			container.commit();

			response.sendRedirect("apptSuccess.jsp");
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			System.out.println("Date-time format parsing error\n");
			response.sendRedirect("apptError.jsp");
		}
		
	}

}
